package com.example.demo.trade.service.impl;

import java.time.LocalDateTime;

import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.client.producer.TransactionSendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.nacos.common.utils.UuidUtils;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.common.constant.RocketMqConstant;
import com.example.common.util.IdUtil;
import com.example.demo.trade.dao.TradeOrderMapper;
import com.example.demo.trade.model.TradeOrder;
import com.example.demo.trade.service.TradeOrderService;

import io.seata.core.context.RootContext;

@Service
public class TradeOrderServiceImpl extends ServiceImpl<TradeOrderMapper, TradeOrder> implements TradeOrderService {

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Override
    public void test() {

        TradeOrder order = new TradeOrder() //
            .setId(IdUtil.getId()) //
            .setMemberId(12345678L) //
            //            .setDate(LocalDate.now()) //
            .setTrainCode(UuidUtils.generateUuid()) //
        ;

        Message<TradeOrder> message = MessageBuilder.withPayload(order) //
            .setHeader("id3", order.getId()) //
            .build();

        TransactionSendResult transactionSendResult = rocketMQTemplate.sendMessageInTransaction(RocketMqConstant.TEST_GROUP, RocketMqConstant.TEST_TOPIC, message, order.getId());

        if (transactionSendResult.getSendStatus() == SendStatus.SEND_OK) {
            System.out.println("half 消息发送成功");
            return;
        }

        System.out.println("half 消息发生失败");

    }

    @Override
    @Transactional
    public void save1(TradeOrder order) {

        String xid = RootContext.getXID();
        System.out.println("seata id: " + xid);

        save(order);

        LambdaUpdateWrapper<TradeOrder> updateWrapper = new UpdateWrapper<TradeOrder>().lambda() //
            .set(TradeOrder::getUpdateTime, LocalDateTime.now()) //
            .eq(TradeOrder::getId, 70) //
        ;
        update(updateWrapper);

        //        System.out.println(1 / 0);

    }

}
